#!/usr/bin/python

"""
    Class: config, a class to read config file or load variable value
"""

import os
import ConfigParser

from exception import ConfigurationFileNotFound
from exception import ConfigurationFileParserError

class Config(object):

    """
    _file: specified config file path
    """
    _file = "";

    """
    _items: a key value pair list for config items
    """
    _items = None;

    """
    constructor: intialize _file and _items
    """
    def __init__(self):
        super(Config, self).__init__();
        self._file = ""
        self.items = None
        return

    """
    set_file: set configuration file path
    """
    def read_configuration_file(self, file):
        if file is None or len(file) == 0:
            raise ConfigurationFileParserError("[Core][Config]Parameter file is not a valid value")

        if not os.path.exists(file):
            raise ConfigurationFileNotFound("[Core][Config]File %s can not be found" % (file))

        try:
            self._file = file
            self._parse_configuration_ini(self._file)
        except KeyError,e:
            raise ConfigurationFileParserError("[Core][Config]File %s can not be parsed, reason:%s" % (file, e)) 
        except ConfigParser.Error,e:
            raise ConfigurationFileParserError("[Core][Config]File %s can not be parsed, reason %s" % (file, e))
        return

    """
    _parse_confiraution_ini: use ConfigParser to parse configuration ini file
    """
    def _parse_configuration_ini(self, file):
        config = ConfigParser.ConfigParser()
        config.read(file)
        if len(config.sections()):
            self._items = dict()
            for section in config.sections():
                section_list = config.items(section)
                if not self._items.has_key(section):
                    self._items[section] = dict()
                for key,val in section_list:
                    self._items[section][key] = val
                del section_list
        return

    """
    get_item: get item by session and name keyword
    """
    def get_item(self, section, name):
        if section is None or section == "":
            return None
        if name is None or name == "":
            return None
        try:
            if not self._items.has_key(section):
                return None
            if not self._items[section].has_key(name):
                return None
            return self._items[section][name]
        except KeyError:
            return None


    """
    get_all_items: get all items from configuration file
    """
    def get_all_items(self):
        if self._items is None:
            return {}
        else:
            return self._items


if __name__ == "__main__":
    cfg = Config()
    cfg.read_configuration_file("/home/APScheduler/configuration.ini")
    interval_check = cfg.get_item('server', 'interval_check')
    all_items = cfg.get_all_items()
    print (interval_check)
    print (all_items)
